package com.carl.dataSources;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.carl.dataSources.config.DataSourceNames;
import com.carl.dataSources.config.localRoutingDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfig {

    @Bean(name="firstDataSource")
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name="secondDataSource")
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name="dataSource")
    @Primary
    public localRoutingDataSource dataSource(@Qualifier("firstDataSource")DataSource firstDataSource,
                                             @Qualifier("secondDataSource")DataSource secondDataSource) {
        localRoutingDataSource localRoutingDataSource = new localRoutingDataSource();
        localRoutingDataSource.setDefaultTargetDataSource(firstDataSource);
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
        targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
        localRoutingDataSource.setTargetDataSources(targetDataSources);
        localRoutingDataSource.afterPropertiesSet();
        return localRoutingDataSource;
    }
}
